package com.bzsg.rightsManagementSystem.config.security_config

import com.bzsg.rightsManagementSystem.service.PermissionService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.ConfigAttribute
import org.springframework.security.access.SecurityConfig
import org.springframework.security.web.FilterInvocation
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource
import org.springframework.stereotype.Component

@Component
class CustomizeFilterInvocationSecurityMetadataSource : FilterInvocationSecurityMetadataSource{
    @Autowired
    lateinit var permissionService: PermissionService
    @Throws(IllegalArgumentException::class)
    override fun getAttributes(o: Any): Collection<ConfigAttribute>? {
        //获取请求地址
        val requestUrl = (o as FilterInvocation).requestUrl
        val realUrls = requestUrl.split("\\?".toRegex(), limit = 2).toTypedArray()
        val realUrl = realUrls[0]
        //查询具体某个接口的权限
        val permissionList = permissionService.selectListByPath(realUrl)
        if (permissionList.isNullOrEmpty()) {
            //请求路径没有配置权限，表明该请求接口可以任意访问
            return null
        }
        val attributes = arrayOfNulls<String>(permissionList.size)
        for (i in permissionList.indices) {
            attributes[i] = permissionList[i].permissionCode
        }
        return SecurityConfig.createList(*attributes)
    }

    override fun getAllConfigAttributes(): MutableCollection<ConfigAttribute>? {
        return null
    }

    override fun supports(aClass: Class<*>?): Boolean {
        return true
    }
}